package com.wdb.modules.system.rest;

import cn.hutool.core.collection.CollectionUtil;
import com.wdb.base.BaseEntity;
import com.wdb.exception.BadRequestException;
import com.wdb.modules.system.domain.Menu;
import com.wdb.modules.system.domain.dto.MenuExcelDTO;
import com.wdb.modules.system.domain.vo.MenuQueryCriteria;
import com.wdb.modules.system.service.MenuService;
import com.wdb.utils.FileUtil;
import com.wdb.utils.PageResult;
import com.wdb.utils.PageUtil;
import com.wdb.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: wendaobai@qq.com
 * @date: 2024/1/17 0017 16:41
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "系统：菜单管理")
@RequestMapping("/api/menus")
@Slf4j
public class MenuController {
  private static final String ENTITY_NAME = "menu";
  @Autowired MenuService menuService;

  @GetMapping(value = "/build")
  @ApiOperation("获取前端所需菜单")
  public ResponseEntity<Object> buildMenus() {
    List<Menu> menuList = menuService.findByUser(SecurityUtils.getCurrentUserId());
    List<Menu> menus = menuService.buildTree(menuList);
    log.info("menus tree--{}--:",menuList, menus);
    return new ResponseEntity<>(menuService.buildMenus(menus), HttpStatus.OK);
  }

  @GetMapping
  @ApiOperation("查询菜单")
  public ResponseEntity<PageResult<Menu>> queryMenu(MenuQueryCriteria menuQueryCriteria)
      throws IllegalAccessException {
    log.info("bbbb");
    List<Menu> menus = menuService.queryAll(menuQueryCriteria, true);
    return new ResponseEntity(PageUtil.toPage(menus), HttpStatus.OK);
  }

  @ApiOperation("返回全部菜单")
  @GetMapping("/lazy")
  public ResponseEntity<List<Menu>> queryAllMenu(@RequestParam Long pid) {
    return new ResponseEntity<>(menuService.getMenus(pid), HttpStatus.OK);
  }

  @ApiOperation("新建菜单")
  @PostMapping
  public ResponseEntity<Object> createMenu(@Validated @RequestBody Menu resources) {
    log.info("xx:{}", resources);
    if (resources.getId() != null) {
      throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID");
    }
    menuService.create(resources);
    return new ResponseEntity<>("ok", HttpStatus.CREATED);
  }

  @ApiOperation("删除菜单")
  @DeleteMapping
  public ResponseEntity<Object> DeleteMenusByIds(@RequestBody List<Long> ids) {
    log.warn("ids--{}", ids);
    Set<Menu> menuSet = new HashSet<>();
    for (Long id : ids) {
      menuSet.add(menuService.getById(id));
      List<Menu> menuList = menuService.getMenus(id);
      menuService.getChildMenus(menuList, menuSet);
      log.info("ids---{}", menuSet);
    }
    menuService.delete(menuSet);
    return new ResponseEntity<>("ok", HttpStatus.OK);
  }

  @ApiOperation("查询菜单:根据ID获取同级与上级数据")
  @PostMapping("/superior")
  public ResponseEntity<List<Menu>> getMenuSuperior(@RequestBody List<Long> ids) {
    Set<Menu> menus = new LinkedHashSet<>();
    if (CollectionUtil.isNotEmpty(ids)) {
      for (Long id : ids) {
        Menu menu = menuService.findById(id);
        List<Menu> menuList = menuService.getSuperior(menu, new ArrayList<>());
        for (Menu data : menuList) {
          if (data.getId().equals(menu.getPid())) {
            data.setSubCount(data.getSubCount() - 1);
          }
        }
        menus.addAll(menuList);
      }
      // 编辑菜单时不显示自己以及自己下级的数据，避免出现PID数据环形问题
      menus = menus.stream().filter(i -> !ids.contains(i.getId())).collect(Collectors.toSet());
      return new ResponseEntity<>(menuService.buildTree(new ArrayList<>(menus)), HttpStatus.OK);
    }
    return new ResponseEntity<>(menuService.getMenus(null), HttpStatus.OK);
  }
  @ApiOperation("修改菜单")
  @PutMapping
  public ResponseEntity<Object> updateMenu(@Validated(Menu.Update.class) @RequestBody Menu resources) {
    menuService.update(resources);
    return new ResponseEntity<>("ok", HttpStatus.OK);
  }
  // 导出excel
  @ApiOperation("导出菜单数据")
  @GetMapping(value = "/download")
  public void download(MenuQueryCriteria criteria, HttpServletResponse response) throws Exception {
    List<Menu> menuList = menuService.queryAll(criteria, false);
    ArrayList<MenuExcelDTO> dataList = new ArrayList<>();
    for (Menu menu : menuList) {
      MenuExcelDTO menuExcelDTO = new MenuExcelDTO();
      menuExcelDTO.setTitle(menu.getTitle());
      menuExcelDTO.setPath(menu.getPath());
      menuExcelDTO.setCreateTime(menu.getCreateTime());
      menuExcelDTO.setUpdateTime(menu.getUpdateTime());
      dataList.add(menuExcelDTO);
    }
    FileUtil.exportToExcel(response, dataList, MenuExcelDTO.class);
    // // 模拟从数据库获取需要导出的数据
    // ArrayList<Map<String, Object>> list = new ArrayList<>();
    // for (Menu menu : menuList) {
    //   Map<String, Object> map = new LinkedHashMap<>();
    //   map.put("菜单标题", menu.getTitle());
    //   map.put("菜单类型", menu.getType());
    //   map.put("权限标识", menu.getPermission());
    //   map.put("外链菜单", menu.getIFrame());
    //   map.put("菜单可见", menu.getHidden());
    //   map.put("创建日期", menu.getCreateTime());
    //   list.add(map);
    // }
    // FileUtil.downloadExcel(list, response);
  }

}
